﻿using UnityEngine;
using UnityEngine.UI;
using ZCUIManager;

namespace ZCMain
{
    public class MainZoomView : UIBaseView
    {
        #region
        private float m_Zoom;
        private Vector2 m_Point;

        public override void Initialize(eUIType uiType, GameObject go)
        {
            base.Initialize(uiType, go);
            m_Point = Vector2.one * 0.5f;
            Hide();
        }

        /// <summary>
        /// 重写mainTexture
        /// </summary>
        public override Texture mainTexture
        {
            get
            {
                if (m_Texture == null && ProgramManager.mainCanvasRender.PaperA != null)
                {
                    m_Texture = ProgramManager.mainCanvasRender.PaperA.RenderTexture;
                }
                return base.mainTexture;
            }
        }

        /// <summary>
        /// 重写OnPopulateMesh
        /// </summary>
        /// <param name="vh"></param>
        protected override void OnPopulateMesh(VertexHelper vh)
        {
            Texture tex = mainTexture;
            vh.Clear();
            if (tex != null)
            {
                var r = GetPixelAdjustedRect();
                var v = new Vector4(r.x, r.y, r.x + r.width, r.y + r.height);
                var w = r.width / (canvas.pixelRect.width * m_Zoom * 2);
                var h = r.height / (canvas.pixelRect.height * m_Zoom * 2);
                var scaleX = tex.width * tex.texelSize.x * w;
                var scaleY = tex.height * tex.texelSize.y * h;
                {
                    var color32 = color;
                    vh.AddVert(new Vector3(v.x, v.y), color32, (new Vector2(-w, -h) + m_Point));
                    vh.AddVert(new Vector3(v.x, v.w), color32, (new Vector2(-w, scaleY) + m_Point));
                    vh.AddVert(new Vector3(v.z, v.w), color32, (new Vector2(scaleX, scaleY) + m_Point));
                    vh.AddVert(new Vector3(v.z, v.y), color32, (new Vector2(scaleX, -h) + m_Point));

                    vh.AddTriangle(0, 1, 2);
                    vh.AddTriangle(2, 3, 0);
                }
            }
        }

        public float ZoomValue
        {
            get
            {
                return m_Zoom;
            }
            set
            {
                m_Zoom = value;
            }
        }

        public void SetPoint(Vector2 point)
        {
            m_Point = point / canvas.pixelRect.size;
            SetVerticesDirty();
        }
        #endregion
    }
}
